#include <stdio.h>
#include <string.h>
#include "pub_log.h"

int g_Fd;
struct stCommCmd
{
    int type;
    char buffer[128];	/*信息*/
};
int main(int argc, char *argv[])
{
    fd_set	stReadFds;/*文件描述符*/
    struct  timeval timeout;
    struct	stCommCmd stCmd;
    int		iUdpFd = 0;
    int		iRc = 0;
    char	buf[1024];

    memset(&stCmd, 0x00, sizeof(struct stCommCmd));

    iRc = WrLog_init_by_logname_logpath("client", "./");
    if(iRc < 0)
    {
        fprintf(stderr, "WrLog_init err!\n");
        WrLog_release();
        return -1;
    }
    slog_info("test");
    iUdpFd = udp_bind("client");
    if( g_Fd < 0 )
    {
        slog_err("create socket error!!g_Fd=[%d]", g_Fd);
        WrLog_release();
        return -1;
    }
    while( 1 )
    {
        slog_fflush();
        memset(&timeout, 0, sizeof(timeout));
        timeout.tv_sec = 30;
        FD_ZERO(&stReadFds);
        FD_SET(iUdpFd, &stReadFds);
        iRc = select(iUdpFd + 2, &stReadFds, NULL, NULL, &timeout);
        if(iRc < 0)
        {
            if(errno == EINTR)
            {
                slog_err("time interpute");
                continue;
            }
            else
            {
                slog_err("select error errno=[%d][%s]", errno, strerror(errno));
                WrLog_release();
                return -1;
            }
        }
        else if(iRc == 0)
        {
            /*表示超时*/
            slog_info("select timeout, no data received!");
            continue;
        }
        else if( FD_ISSET(iUdpFd, &stReadFds) )
        {
            /**/
            slog_info("Data is available now.");
            memset(&stCmd, 0x00, sizeof(struct stCommCmd));
            iRc = udp_recv(iUdpFd, (char *)&stCmd, sizeof(struct stCommCmd));
            if(  iRc < 0 )
            {
                slog_err("udp_recv err! errno=[%d][%s]", errno, strerror(errno));
                WrLog_release();
                return -1;
            }
            slog_info("udp_recv data.[%d %s]", stCmd.type, stCmd.buffer);
            printf("udp_recv data.[%d %s]", stCmd.type, stCmd.buffer);
            udp_send(iUdpFd, (char *)&stCmd, sizeof(struct stCommCmd), "swman");
        }
    }

    WrLog_release();
    return 0;
}
